package com.example.tests;

import com.example.framework.ContactData;
import com.example.framework.GroupData;
import com.example.framework.HelperManager;
import com.example.utils.TestDataGenerator;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;

import java.io.File;
import java.io.FileReader;
import java.util.*;

import static com.example.utils.ContactDataGenerator.generateRandomContacts;
import static com.example.utils.GroupDataGenerator.generateRandomGroups;

public class TestManager {

    protected static HelperManager manager;
    protected TestDataGenerator dataGen;
    Random rnd = new Random();

    @BeforeTest
    protected void setUp() throws Exception {
        String configFile = System.getProperty("configFile", "application.properties");
        Properties properties = new Properties();
        properties.load(new FileReader(new File(configFile)));
        manager = new HelperManager(properties);
        dataGen = new TestDataGenerator();
    }

    @AfterTest
    protected void tearDown() throws Exception {
        manager.stopDriver();
    }

    @DataProvider
    public Iterator<Object[]> validContact(){
        List<ContactData> contacts = generateRandomContacts(5);
        List<Object[]> list = convertContactToDataProviderFormat(contacts);

        return list.iterator();
    }

    public List<Object[]> convertContactToDataProviderFormat(List<ContactData> contacts) {
        List<Object[]> list = new ArrayList<Object[]>();
        for (ContactData contact: contacts) {
            list.add(new Object[]{contact});
        }
        return list;
    }

    @DataProvider
    public Object[][] validGroup() {
        return new Object[][] {
                {new GroupData()
                        .withName("")
                        .withHeader("")
                        .withHeader("")
                },
                {new GroupData()
                        .withName(dataGen.getRandomStringWithRandomLength(25))
                        .withHeader(dataGen.getRandomStringWithRandomLength(25))
                        .withFooter(dataGen.getRandomStringWithRandomLength(25))
                },
                {new GroupData()
                        .withName(dataGen.getRandomString(10))
                        .withHeader(dataGen.getRandomString(10))
                        .withFooter(dataGen.getRandomString(10))
                }
        };
    }

    @DataProvider
    public Iterator<Object[]> randomGroupData(){
        List<GroupData> groups = generateRandomGroups(5);
        List<Object[]> list = convertGroupToDataProviderFormat(groups);

        return list.iterator();
    }

    public List<Object[]> convertGroupToDataProviderFormat(List<GroupData> groups) {
        List<Object[]> list = new ArrayList<Object[]>();
        for (GroupData group: groups) {
            list.add(new Object[]{group});
        }
        return list;
    }
}
